import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_animation/Utils/ColorUtil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:photo_manager/photo_manager.dart';

class ImageUtils {
  static void pickImage(BuildContext context,ValueChanged callback) {
    showMaterialModalBottomSheet(
      context: context,
      barrierColor: Colors.transparent,
      backgroundColor: ColorUtil.colorWhite,
      builder: (w) {
        return PhotoList();
      },
    ).then((value) {
      callback(value);
    });
  }
}

class PhotoList extends StatefulWidget {
  const PhotoList({super.key});

  @override
  State<PhotoList> createState() => _PhotoListState();
}

class _PhotoListState extends State<PhotoList> with TickerProviderStateMixin{
  final int _sizePerPage = 50;

  // 相册地址列表
  List<AssetPathEntity>? _allPath;
  AssetPathEntity? _currentPath;
  // 所有照片资源
  List<AssetEntity>? _entities;
  // 选中的照片资源
  final ValueNotifier<List<AssetEntity>> _chosenEntities = ValueNotifier([]);
  // 选中的照片资源（文件类型，做缓存处理，防止每次视图更新都会闪一下）
  final List<File> _chosenEntitiesFile = [];
  final _animatedListKey = GlobalKey<AnimatedListState>();

  int _totalEntitiesCount = 0;
  int _page = 0;
  bool _isLoading = false;
  bool _isLoadingMore = false;
  bool _hasMoreToLoad = true;

  // 是否展示相册选择
  bool showAlbum = false;
  // 相册当前视图
  final ValueNotifier<CrossFadeState> _albumCrossFadeState = ValueNotifier(CrossFadeState.showFirst);
  // 相册选择动画控制器
  late final AnimationController _albumAnimationController = AnimationController(
    duration: const Duration(milliseconds: 200),
    reverseDuration: const Duration(milliseconds: 200),
    vsync: this,
  );

  // 已选照片当前视图
  final ValueNotifier<CrossFadeState> _chosenCrossFadeState = ValueNotifier(CrossFadeState.showFirst);


  @override
  void initState() {
    super.initState();
    _init();
  }

  _init() async {
    setState(() {
      _isLoading = true;
    });
    // 请求权限
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    if (!mounted) {
      return;
    }
    // 没有权限，前往设置
    if (!ps.hasAccess) {
      toAppSetting("请确保APP已授权允许照片权限");
      setState(() {
        _isLoading = false;
      });
    }
    // 相册地址列表
    _allPath = await PhotoManager.getAssetPathList(
      filterOption: FilterOptionGroup(
        imageOption: const FilterOption(
          sizeConstraint: SizeConstraint(ignoreSize: true),
        ),
      ),
      type: RequestType.image,
    );
    if (!mounted) {
      return;
    }
    // 没找到照片地址列表
    if (_allPath!.isEmpty) {
      setState(() {
        _isLoading = false;
      });
      SmartDialog.showToast('暂无照片',displayType: SmartToastType.last);
      return;
    }

    _loadAssets(0);
  }

  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(height: MediaQuery.of(context).padding.top),
        buildBar(),
        Expanded(
          child: Stack(
            children: [
              buildBody(context),
              buildAlbumChoose(),
            ],
          ),
        ),
      ],
    );
  }

  /// 顶部信息
  buildBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Navigator.pop(context);
            },
            child: Image.asset(
              'assets/images/ic_s_s_xmark_outlined_20.webp',
              width: 24,
              height: 24,
            ),
          ),
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (showAlbum) {
                  albumStatusChange(false);
                } else {
                  albumStatusChange(true);
                }
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: Text(
                      (_currentPath?.name == null || _currentPath!.name == 'Recent') ? '所有照片' : _currentPath!.name,
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.end,
                    ),
                  ),
                  SizedBox(width: 5),
                  RotationTransition(
                    turns: Tween(begin: 0.0, end: 0.5).animate(_albumAnimationController),
                    child: Image.asset(
                      'assets/images/tools_media_import_ic_down_chevron_black.png',
                      width: 16,
                      height: 16,
                      color: ColorUtil.colorBlack,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 相册选择视图
  buildAlbumChoose() {
    if (_allPath == null) {
      return SizedBox.shrink();
    }
    return ValueListenableBuilder(
      valueListenable: _albumCrossFadeState,
      builder:(context, value, child) {
        return AnimatedCrossFade(
          firstCurve: Curves.linear,
          secondCurve: Curves.linear,
          firstChild: Container(),
          secondChild: Container(
            color: Colors.white,
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Column(
                children: _allPath!.map<Widget>((AssetPathEntity item) {
                  int index = _allPath!.indexOf(item);
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      _currentPath = _allPath![index];
                      albumStatusChange(false);
                      _loadAssets(index);
                    },
                    child: Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 10),
                      decoration: BoxDecoration(
                        border: Border(bottom: BorderSide(color: ColorUtil.color999999_30, width: 0.5)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(_allPath![index].name == 'Recent' ? '所有照片' : _allPath![index].name),
                          SizedBox(height: 5,),
                          FutureBuilder(
                            future: _allPath![index].assetCountAsync,
                            builder: (context, snapshot) {
                              if (snapshot.connectionState == ConnectionState.done) {
                                return Text(
                                  snapshot.data.toString(),
                                  style: TextStyle(
                                    color: ColorUtil.color999999,
                                    fontSize: 12,
                                  ),
                                );
                              }
                              return Container();
                            }
                          ),
                        ],
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
          duration: Duration(milliseconds: 200),
          crossFadeState: _albumCrossFadeState.value,
        );
      },
    );
  }

  /// 相册选择动画状态切换
  albumStatusChange(bool menuStatus) {
    showAlbum = menuStatus;
    if (showAlbum) {
      _albumAnimationController.forward();
      _albumCrossFadeState.value = CrossFadeState.showSecond;
    } else {
      _albumAnimationController.reverse();
      _albumCrossFadeState.value = CrossFadeState.showFirst;
    }
  }

  buildBody(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator.adaptive());
    }
    if (_entities?.isNotEmpty != true) {
      return const Center(child: Text('此相册无照片'));
    }
    return Column(
      children: [
        Expanded(
          child: GridView.custom(
            shrinkWrap: true,
            padding: const EdgeInsets.all(0),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 2,
              crossAxisSpacing: 2,
            ),
            childrenDelegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                if (index == _entities!.length - 8 && !_isLoadingMore && _hasMoreToLoad) {
                  _loadMoreAsset();
                }

                AssetEntity currentAssetEntity = _entities![index];

                return FutureBuilder(
                  future: currentAssetEntity.originFile,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return GestureDetector(
                        onTap: () {
                          if (_chosenEntities.value.contains(currentAssetEntity)) {
                            _removePhoto(_chosenEntities.value.indexOf(currentAssetEntity));
                          } else {
                            if (_chosenEntities.value.length >= 9) {
                              SmartDialog.showToast('最多只能选择9张照片',displayType: SmartToastType.last);
                              return;
                            }
                            _addPhoto(_chosenEntities.value.length, currentAssetEntity);
                          }
                        },
                        child: Stack(
                          alignment: AlignmentDirectional.center,
                          fit: StackFit.expand,
                          children: [
                            Image.file(
                              snapshot.data!,
                              fit: BoxFit.cover,
                            ),
                            ValueListenableBuilder(
                              valueListenable: _chosenEntities,
                              builder: (context, value, child) {
                                return Positioned(
                                  top: 5,
                                  right: 5,
                                  child: Container(
                                    width: 26,
                                    height: 26,
                                    decoration: BoxDecoration(
                                      border: Border.all(color: ColorUtil.colorWhite, width: 2),
                                      shape: BoxShape.circle,
                                      color: value.contains(currentAssetEntity) ? ColorUtil.primary : ColorUtil.color999999_30,
                                    ),
                                    child: Center(
                                      child: Text(
                                        value.contains(currentAssetEntity) ? (value.indexOf(currentAssetEntity)+1).toString() : '',
                                        style: TextStyle(
                                          color: ColorUtil.colorWhite,
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      );
                    }
                    return Container();
                  },
                );
              },
              childCount: _entities!.length,
              findChildIndexCallback: (Key key) {
                // Re-use elements.
                if (key is ValueKey<int>) {
                  return key.value;
                }
                return null;
              },
            ),
          ),
        ),
        ValueListenableBuilder(
          valueListenable: _chosenCrossFadeState,
          builder:(context, value, child) {
            return AnimatedCrossFade(
              firstCurve: Curves.linear,
              secondCurve: Curves.linear,
              firstChild: Container(),
              secondChild: Container(
                padding: EdgeInsets.symmetric(vertical: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    SizedBox(
                      width: double.infinity,
                      height: 60,
                      child: AnimatedList(
                        key: _animatedListKey,
                        shrinkWrap: true,
                        scrollDirection: Axis.horizontal,
                        initialItemCount: _chosenEntitiesFile.length,
                        padding: EdgeInsets.only(right: 10),
                        itemBuilder: (context, index, animation) => _buildAnimatedItem(_chosenEntitiesFile[index], index, animation),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context, _chosenEntitiesFile);
                      },
                      child: Container(
                        margin: const EdgeInsets.all(10),
                        padding: const EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: ColorUtil.primary,
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Text(
                          '下一步(${_chosenEntitiesFile.length})' ,
                          style: TextStyle(
                            color: ColorUtil.colorWhite,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              duration: Duration(milliseconds: 200),
              crossFadeState: _chosenCrossFadeState.value,
            );
          },
        ),
      ],
    );
  }

  /// 已选照片item
  _buildAnimatedItem(File item, int index, Animation<double> animation) {
    return SlideTransition(
      position: Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0)).animate(
        CurvedAnimation(
            parent: animation,
            curve: Curves.linear,
            reverseCurve: Curves.linear)),
      child: Container(
        padding: const EdgeInsets.only(left: 10),
        child: Stack(
          children: [
            Card(
              margin: EdgeInsets.all(0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadiusDirectional.circular(5),
              ),
              clipBehavior: Clip.antiAlias,
              child: Image.file(
                item,
                fit: BoxFit.cover,
                width: 60,
                height: 60,
              ),
            ),
            Positioned(
              top: 0,
              right: 0,
              child: GestureDetector(
                onTap: () {
                  _removePhoto(index);
                },
                child: Container(
                  padding: EdgeInsets.all(2),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(5),
                      bottomLeft: Radius.circular(5),
                    ),
                    color: ColorUtil.colorBlack_30,
                  ),
                  child: Icon(
                    Icons.close,
                    color: ColorUtil.colorWhite,
                    size: 12,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 添加照片
  _addPhoto(int index, AssetEntity item) async {
    File? file = await item.originFile;
    _chosenEntitiesFile.insert(index, file!);
    _chosenEntities.value.insert(index, item);
    _animatedListKey.currentState?.insertItem(index);
    _chosenEntities.value = [..._chosenEntities.value];
    if (_chosenEntities.value.isEmpty) {
      _chosenCrossFadeState.value = CrossFadeState.showFirst;
    } else {
      _chosenCrossFadeState.value = CrossFadeState.showSecond;
    }
  }
  /// 删除照片
  _removePhoto(int index) async {
    final item = _chosenEntitiesFile.removeAt(index);
    _chosenEntities.value.removeAt(index);
    _animatedListKey.currentState?.removeItem(index, (context, animation) => _buildAnimatedItem(item, index, animation),duration: Duration(milliseconds: 0));
    for (int i = index; i < _chosenEntities.value.length; i++) {
      _animatedListKey.currentState?.removeItem(
        i,
        (context, animation) => const SizedBox.shrink(),
        duration: Duration(milliseconds: 0),
      );
      _animatedListKey.currentState?.insertItem(
        i,
        duration: Duration(milliseconds: 300),
      );
    }
    _chosenEntities.value = [..._chosenEntities.value];
        if (_chosenEntities.value.isEmpty) {
      _chosenCrossFadeState.value = CrossFadeState.showFirst;
    } else {
      _chosenCrossFadeState.value = CrossFadeState.showSecond;
    }
  }

  /// 请求相册列表
  _loadAssets(int pathIndex) async {
    if (!_isLoading) {
      setState(() {
        _isLoading = true;
      });
    }

    _page = 0;
    
    setState(() {
      _currentPath = _allPath![pathIndex];
    });
    _totalEntitiesCount = await _currentPath!.assetCountAsync;
    final List<AssetEntity> entities = await _currentPath!.getAssetListPaged(
      page: 0,
      size: _sizePerPage,
    );
    if (!mounted) {
      return;
    }
    setState(() {
      _entities = entities;
      _isLoading = false;
      _hasMoreToLoad = _entities!.length < _totalEntitiesCount;
    });
  }

  /// 加载更多
  _loadMoreAsset() async {
    final List<AssetEntity> entities = await _currentPath!.getAssetListPaged(
      page: _page + 1,
      size: _sizePerPage,
    );
    if (!mounted) {
      return;
    }
    setState(() {
      _entities!.addAll(entities);
      _page++;
      _hasMoreToLoad = _entities!.length < _totalEntitiesCount;
      _isLoadingMore = false;
    });
  }

  
  toAppSetting(string) {
    SmartDialog.show(
      builder: (context) {
        return AlertDialog(
          title: Text(string),
          actions: <Widget>[
            TextButton(
                child: Text(
                  '取消',
                  style: TextStyle(color: Colors.grey),
                ),
                onPressed: () {
                  SmartDialog.dismiss();
                }),
            TextButton(
              child: Text(
                '去设置',
                style: TextStyle(color: Colors.blue),
              ),
              onPressed: () {
                SmartDialog.dismiss();
                PhotoManager.openSetting();
              },
            ),
          ],
        );
      }
    );
  }
}